package com.nananren.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nananren.anno.OperateLogLog;
import com.nananren.common.MyThreadLocal;
import com.nananren.common.Result;
import com.nananren.domain.Borrow;
import com.nananren.domain.Category;
import com.nananren.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    // 新增分类
    @PostMapping
    @OperateLogLog
    public Result save(@RequestBody Category category) {
        log.info("新增的分类信息为：{}", category.toString());
        // 条件构造器
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询所有被删除的数据
        categoryLambdaQueryWrapper.eq(Category::getIsDeleted, 0);
        categoryLambdaQueryWrapper.eq(Category::getType, category.getType());
        Category categoryInDB = categoryService.getOne(categoryLambdaQueryWrapper);
        if (categoryInDB != null) {
            categoryInDB.setIsDeleted(1);
            categoryInDB.setCreateTime(LocalDateTime.now());
            categoryInDB.setCreateUser(MyThreadLocal.getLocal());
            categoryService.updateById(categoryInDB);
            return Result.success("新增成功");
        }

        // 如果数据库中被删除的数据中没有要添加的元素，则正常添加
        boolean flag = categoryService.save(category);
        System.out.println(flag);
        return flag ? Result.success("新增成功") : Result.error("新增失败");
    }

    // 修改分类
    @PutMapping
    @OperateLogLog
    public Result updateById(@RequestBody Category category) {
        log.info("修改的分类信息为：{}", category.toString());
        boolean flag = categoryService.updateById(category);
        return flag ? Result.success("修改成功") : Result.error("修改失败");
    }

    // 根据id查询分类
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        log.info("根据id查询分类信息，id为{}", id);
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询id和传递id相同且未被删除的分类
        categoryLambdaQueryWrapper.eq(Category::getId, id);
        categoryLambdaQueryWrapper.eq(Category::getIsDeleted, 1);
        Category category = categoryService.getOne(categoryLambdaQueryWrapper);
        return category != null ? Result.success(category) : Result.error("当前分类不存在");
    }

    // 查询所有分类
    @GetMapping
    public Result list() {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询未删除的数据
        categoryLambdaQueryWrapper.eq(Category::getIsDeleted, 1);
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        if (list.size() == 0) {
            return Result.error("暂无数据");
        }
        return Result.success(list);
    }

    // 分类分页查询
    @GetMapping("/page")
    public Result page(int page, int pageSize, String type,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end) {
        log.info("page:{}, pageSize:{}, type:{}, begin:{}, end:{}", page, pageSize, type, begin, end);
        Page<Category> categoryPage = new Page<>(page, pageSize);
        // 条件构造器
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // begin等于null，end不等于null，查询borrow_time小于等于end的所有数据
        categoryLambdaQueryWrapper.le(begin == null && end != null, Category::getCreateTime, end);
        // begin不等于null，end等于null，查询borrow_time大于等于begin的所有数据
        categoryLambdaQueryWrapper.ge(begin != null && end == null, Category::getCreateTime, begin);
        // begin和end都不等于null，查询borrow_time大于等于begin并小于等于end的所有数据
        categoryLambdaQueryWrapper.between(begin != null && end != null, Category::getCreateTime, begin, end);
        // 模糊查询
        categoryLambdaQueryWrapper.like(type != null && type != "", Category::getType, type);
        // 状态为1
        categoryLambdaQueryWrapper.eq(Category::getIsDeleted, 1);
        // 倒序排序
        categoryLambdaQueryWrapper.orderByDesc(Category::getUpdateTime);
        // 分页查询
        categoryService.page(categoryPage, categoryLambdaQueryWrapper);
        // 判断查询得到的总数是否不等于0
        return categoryPage.getTotal() != 0 ? Result.success(categoryPage) : Result.error("暂无数据");
    }

    // 根据id删除分类
    @OperateLogLog
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Long id) {
        log.info("根据id删除分类信息，id为:{}", id);
        // 条件构造器
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getId, id);
        categoryLambdaQueryWrapper.eq(Category::getIsDeleted, 1);
        Category category = categoryService.getOne(categoryLambdaQueryWrapper);
        if (category != null) {
            categoryService.deleteWithBook(id);
            return Result.success("删除成功!!");
        }

        return Result.error("当前分类不存在");
    }

    // 批量删除分类
    @OperateLogLog
    @DeleteMapping("/isDeleted/0")
    public Result delete(@RequestParam("ids") List<Long> ids) {
        log.info("批量删除分类，ids为：{}", ids);
        // 条件构造器
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getIsDeleted, 1);
        categoryLambdaQueryWrapper.in(ids.size() != 0, Category::getId, ids);
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        // 如果相等，说明传递的id所对应的分类都存在
        if (list.size() == ids.size()) {
            // 业务操作
            categoryService.deletesWithBook(ids);

            return Result.success("删除成功");
        }

        return Result.error("当前分类不存在!");
    }



}
